package com.tedu.charging.service.bill.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQBillConfig {
    public static final String BILL_EXCHANGE ="billExchange";
    public static final String BILL_QUEUE ="billQueue";
    public static final String BILL_KEY="bill";

    public static final String DEAD_LETTER_EXCHANGE ="DEAD_LETTER_EXCHANGE";
    public static final String DEAD_LETTER_QUEUE_NAME = "dead.letter.queue";
    public static final String DEAD_LETTER_QUEUE_ROUTING_KEY ="DEAD_LETTER_QUEUE_ROUTING_KEY";
    //申明订单交换机
    @Bean
    public DirectExchange getExchange(){
        DirectExchange directExchange = new DirectExchange(BILL_EXCHANGE);
        return directExchange;
    }
    //申明订单队列
    //org.springframework.amqp.core.Queue
    @Bean
    public Queue getQueue(){
        Map<String, Object> args = new HashMap<>();
        //指定消息的是过期时间2分钟,2*60*1000
        //队列设置过期时间：x-message-ttl，单位：ms（毫秒），这样的话进入队列的所有消息都遵循这个过期时间
        Integer ttl=2*60*1000;
        args.put("x-message-ttl",ttl);
        args.put("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE);
        args.put("x-dead-letter-routing-key",DEAD_LETTER_QUEUE_ROUTING_KEY);
        args.put("x-queue-mode", "lazy"); // 声明为惰性队列, 避免消息积压占用大量内存
        /** @params1 : 队列名称
         *  @params2 : 是否持久化（true：重启后不会消失）
         *  @params3 : 是否独占队列（true：仅限于此连接使用）
         *  @params4 : 是否自动删除（队列内最后一条消息被消费后，队列将自动删除）
         */
        return new Queue(BILL_QUEUE,true,false,false,args);
    }

    //将订单队列绑定到订单交换机上
    @Bean
    public Binding binding(){
        Binding binding = BindingBuilder.bind(getQueue()).to(getExchange()).with(BILL_KEY);
        return binding;
    }

    // 声明死信交换机
    @Bean("deadLetterExchange")
    public TopicExchange deadLetterExchange(){
        return
                new TopicExchange(DEAD_LETTER_EXCHANGE,true,false);
    }

    // 声明死信队列
    @Bean("deadLetterQueue")
    public Queue deadLetterQueue(){

        return new Queue(DEAD_LETTER_QUEUE_NAME,true,false,false);
    }

    // 将死信队列和死信交换机绑定
    @Bean
    public Binding deadLetterBindingB(){
        return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange())
                .with(DEAD_LETTER_QUEUE_ROUTING_KEY);
    }
}
